package com.wxxymaker.edu.service;

import com.blade.ioc.annotation.Bean;
import com.blade.kit.CollectionKit;
import com.wxxymaker.edu.model.entity.ImageInfo;
import com.wxxymaker.edu.utils.FileUtils;
import com.wxxymaker.edu.utils.TimeUtils;
import io.github.biezhi.anima.Anima;
import io.github.biezhi.anima.core.AnimaQuery;
import io.github.biezhi.anima.enums.OrderBy;
import io.github.biezhi.anima.page.Page;

/**
 * @AUTHOR soft
 * @DATE 2018/10/18 16:43
 * @DESCRIBE
 */
@Bean
public class ImageInfoService implements Service<ImageInfo> {

    public Page<ImageInfo> page(Integer type, int page, int size) {
        AnimaQuery<ImageInfo> query = Anima.select().from(ImageInfo.class)
                .order(ImageInfo::getUse0, OrderBy.DESC)
                .order(ImageInfo::getTime, OrderBy.DESC);
        if (type != null) query.where(ImageInfo::getType, type);
        Page<ImageInfo> page1 = query.page(page, size);
        if (CollectionKit.isNotEmpty(page1.getRows())) {
            return page1;
        }
        return null;
    }

    @Override
    public ImageInfo add(ImageInfo imageInfo) {
        imageInfo.setTime(TimeUtils.getTime());
        Integer integer = imageInfo.save().asInt();
        if (integer>0) {
            imageInfo.setId(integer);
            return imageInfo;
        }
        return null;
    }

    @Override
    public ImageInfo delete(Object pk) {
        ImageInfo imageInfo = byId(pk);
        if (imageInfo != null) {
            imageInfo.delete();
            FileUtils.deleteByWebPath(imageInfo.getPath());
            return imageInfo;
        }
        return null;
    }

    @Override
    public boolean change(ImageInfo imageInfo) {
        if (imageInfo.getId() > 0) {
            return imageInfo.update() > 0;
        }
        return false;
    }

    @Override
    public ImageInfo byId(Object pk) {
        return Anima.select().from(ImageInfo.class).byId(pk);
    }
}
